package com.kelvin.oocl.listener;

import java.text.ParseException;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.json.JSONException;
import org.json.JSONObject;

import com.kelvin.oocl.dao.BookDao;
import com.kelvin.oocl.pojo.Book;
import com.kelvin.oocl.util.DateUtil;

public class MyMessageListener implements MessageListener {
	private BookDao bookDao;
	
	public MyMessageListener(BookDao bookDao) {
		this.bookDao = bookDao;
	}
	
	@Override
	public void onMessage(Message message) {
		try {
			TextMessage msg = (TextMessage) message;
			String jsonStr = msg.getText();
			JSONObject json = new JSONObject(jsonStr.trim());
			Book book = toBook(json);
			System.out.println(book);
			bookDao.addBook(book);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	private Book toBook(JSONObject json) {
		try {
			Book book = new Book();
			book.setId(json.getInt("id"));
			book.setBookName(json.getString("bookName"));
			book.setPublishTime(DateUtil.strToDate(json.getString("publishTime"), "yyyy-MM-dd HH:mm:ss"));
			book.setAuthor(json.getString("author"));
			book.setNewBook(json.getBoolean("newBook"));
			book.setPrice(json.getDouble("price"));
			book.setPress(json.getString("press"));
			return book;
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

}
